﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

using MiniTwitter.Net.Twitter;

namespace MiniTwitter
{
    [Serializable]
    public class Filter : PropertyChangedBase, IEditableObject
    {
        private FilterType type;

        [XmlAttribute]
        public FilterType Type
        {
            get { return type; }
            set
            {
                if (type != value)
                {
                    type = value;
                    OnPropertyChanged("Type");
                }
            }
        }

        private string pattern;

        [XmlAttribute]
        public string Pattern
        {
            get { return pattern; }
            set
            {
                if (pattern != value)
                {
                    pattern = value;
                    OnPropertyChanged("Pattern");
                }
            }
        }

        public bool Process(ITwitterItem item)
        {
            switch (Type)
            {
                case FilterType.Text:
                    return item.Text.Contains(Pattern);
                case FilterType.RegexText:
                    return Regex.IsMatch(item.Text, Pattern);
                case FilterType.Name:
                    return string.Compare(item.Sender.ScreenName, Pattern) == 0;
                case FilterType.RegexName:
                    return Regex.IsMatch(item.Sender.ScreenName, Pattern);
            }
            return false;
        }

        private Filter copy;

        public void BeginEdit()
        {
            if (copy == null)
            {
                copy = new Filter();
            }
            copy.Pattern = this.Pattern;
            copy.Type = this.Type;
        }

        public void CancelEdit()
        {
            this.Pattern = copy.Pattern;
            this.Type = copy.Type;
        }

        public void EndEdit()
        {
            copy.Pattern = null;
            copy.Type = FilterType.None;
        }
    }
}
